﻿using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace ServiceLayerManagement
{
    public class BinaryFormatterHelper
    {
        /// <summary>
        /// 保存对象到文件,通过二进制序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="filePath">文件路径</param>
        /// <param name="data">数据对象</param>
        /// <returns></returns>
        public static bool SaveFileByBinary<T>(string filePath, T data)
        {
            bool result = false;
            try
            {
                string strFolder = Path.GetDirectoryName(filePath);
                if (!Directory.Exists(strFolder)) Directory.CreateDirectory(strFolder);

                if (!File.Exists(filePath))
                {
                    string path = Path.GetDirectoryName(filePath);
                    if (!Directory.Exists(path))//判断是否存在
                    {
                        Directory.CreateDirectory(path);
                    }
                }

                using (Stream fStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
                {
                    BinaryFormatter binFormat = new BinaryFormatter();
                    binFormat.Serialize(fStream, data);
                }
                result = true;
            }
            catch { }

            return result;
        }

        /// <summary>
        /// 从文件中读取对象,通过二进制序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static T LoadFileByBinary<T>(string filePath) where T : new()
        {
            T model = new T();

            if (!File.Exists(filePath)) return model;

            using (Stream fStream = File.OpenRead(filePath))
            {
                BinaryFormatter binFormat = new BinaryFormatter();
                model = (T)binFormat.Deserialize(fStream);
            }
            return model;
        }
    }
}
